<!DOCTYPE html>



  


<html class="theme-next gemini use-motion" lang="zh-Hans">
<head><meta name="generator" content="Hexo 3.9.0">
  <meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1">
<meta name="theme-color" content="#222">









<meta http-equiv="Cache-Control" content="no-transform">
<meta http-equiv="Cache-Control" content="no-siteapp">
















  
  
  <link href="/lib/fancybox/source/jquery.fancybox.css?v=2.1.5" rel="stylesheet" type="text/css">







<link href="/lib/font-awesome/css/font-awesome.min.css?v=4.6.2" rel="stylesheet" type="text/css">

<link href="/css/main.css?v=5.1.4" rel="stylesheet" type="text/css">


  <link rel="apple-touch-icon" sizes="180x180" href="/images/apple-touch-icon-next.png?v=5.1.4">


  <link rel="icon" type="image/png" sizes="32x32" href="/images/favicon-32x32-next.png?v=5.1.4">


  <link rel="icon" type="image/png" sizes="16x16" href="/images/favicon-16x16-next.png?v=5.1.4">


  <link rel="mask-icon" href="/images/logo.svg?v=5.1.4" color="#222">





  <meta name="keywords" content="Mysql,">










<meta name="description" content="MySql数据库">
<meta name="keywords" content="Mysql">
<meta property="og:type" content="article">
<meta property="og:title" content="MySql数据库">
<meta property="og:url" content="http://yoursite.com/2019/04/11/Service/MySql数据库/index.html">
<meta property="og:site_name" content="Dan&#39;s Blog">
<meta property="og:description" content="MySql数据库">
<meta property="og:locale" content="zh-Hans">
<meta property="og:image" content="http://yoursite.com/images/数据库连接查询相关图.jpg">
<meta property="og:updated_time" content="2020-08-01T15:13:55.257Z">
<meta name="twitter:card" content="summary">
<meta name="twitter:title" content="MySql数据库">
<meta name="twitter:description" content="MySql数据库">
<meta name="twitter:image" content="http://yoursite.com/images/数据库连接查询相关图.jpg">



<script type="text/javascript" id="hexo.configurations">
  var NexT = window.NexT || {};
  var CONFIG = {
    root: '/',
    scheme: 'Gemini',
    version: '5.1.4',
    sidebar: {"position":"left","display":"post","offset":12,"b2t":false,"scrollpercent":false,"onmobile":false},
    fancybox: true,
    tabs: true,
    motion: {"enable":true,"async":false,"transition":{"post_block":"fadeIn","post_header":"slideDownIn","post_body":"slideDownIn","coll_header":"slideLeftIn","sidebar":"slideUpIn"}},
    duoshuo: {
      userId: '0',
      author: '博主'
    },
    algolia: {
      applicationID: '',
      apiKey: '',
      indexName: '',
      hits: {"per_page":10},
      labels: {"input_placeholder":"Search for Posts","hits_empty":"We didn't find any results for the search: ${query}","hits_stats":"${hits} results found in ${time} ms"}
    }
  };
</script>



  <link rel="canonical" href="http://yoursite.com/2019/04/11/Service/MySql数据库/">





  <title>MySql数据库 | Dan's Blog</title>
  





  <script type="text/javascript">
    var _hmt = _hmt || [];
    (function() {
      var hm = document.createElement("script");
      hm.src = "https://hm.baidu.com/hm.js?f038ff2e430cd3c47bcf12292960ce88";
      var s = document.getElementsByTagName("script")[0];
      s.parentNode.insertBefore(hm, s);
    })();
  </script>




</head>

<body itemscope itemtype="http://schema.org/WebPage" lang="zh-Hans">

  
  
    
  

  <div class="container sidebar-position-left page-post-detail">
    <div class="headband"></div>

    <header id="header" class="header" itemscope itemtype="http://schema.org/WPHeader">
      <div class="header-inner"><div class="site-brand-wrapper">
  <div class="site-meta ">
    

    <div class="custom-logo-site-title">
      <a href="/" class="brand" rel="start">
        <span class="logo-line-before"><i></i></span>
        <span class="site-title">Dan's Blog</span>
        <span class="logo-line-after"><i></i></span>
      </a>
    </div>
      
        <p class="site-subtitle"></p>
      
  </div>

  <div class="site-nav-toggle">
    <button>
      <span class="btn-bar"></span>
      <span class="btn-bar"></span>
      <span class="btn-bar"></span>
    </button>
  </div>
</div>

<nav class="site-nav">
  

  
    <ul id="menu" class="menu">
      
        
        <li class="menu-item menu-item-home">
          <a href="/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-home"></i> <br>
            
            首页
          </a>
        </li>
      
        
        <li class="menu-item menu-item-tags">
          <a href="/tags/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-tags"></i> <br>
            
            标签
          </a>
        </li>
      
        
        <li class="menu-item menu-item-categories">
          <a href="/categories/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-th"></i> <br>
            
            分类
          </a>
        </li>
      

      
        <li class="menu-item menu-item-search">
          
            <a href="javascript:;" class="popup-trigger">
          
            
              <i class="menu-item-icon fa fa-search fa-fw"></i> <br>
            
            搜索
          </a>
        </li>
      
    </ul>
  

  
    <div class="site-search">
      
  <div class="popup search-popup local-search-popup">
  <div class="local-search-header clearfix">
    <span class="search-icon">
      <i class="fa fa-search"></i>
    </span>
    <span class="popup-btn-close">
      <i class="fa fa-times-circle"></i>
    </span>
    <div class="local-search-input-wrapper">
      <input autocomplete="off" placeholder="搜索..." spellcheck="false" type="text" id="local-search-input">
    </div>
  </div>
  <div id="local-search-result"></div>
</div>



    </div>
  
</nav>



 </div>
    </header>

    <main id="main" class="main">
      <div class="main-inner">
        <div class="content-wrap">
          <div id="content" class="content">
            

  <div id="posts" class="posts-expand">
    

  

  
  
  

  <article class="post post-type-normal" itemscope itemtype="http://schema.org/Article">
  
  
  
  <div class="post-block">
    <link itemprop="mainEntityOfPage" href="http://yoursite.com/2019/04/11/Service/MySql数据库/">

    <span hidden itemprop="author" itemscope itemtype="http://schema.org/Person">
      <meta itemprop="name" content="Dan">
      <meta itemprop="description" content>
      <meta itemprop="image" content="/uploads/avatar.jpg">
    </span>

    <span hidden itemprop="publisher" itemscope itemtype="http://schema.org/Organization">
      <meta itemprop="name" content="Dan's Blog">
    </span>

    
      <header class="post-header">

        
        
          <h1 class="post-title" itemprop="name headline">MySql数据库</h1>
        

        <div class="post-meta">
          <span class="post-time">
            
              <span class="post-meta-item-icon">
                <i class="fa fa-calendar-o"></i>
              </span>
              
                <span class="post-meta-item-text">发表于</span>
              
              <time title="创建于" itemprop="dateCreated datePublished" datetime="2019-04-11T12:40:26+08:00">
                2019-04-11
              </time>
            

            

            
          </span>

          
            <span class="post-category">
            
              <span class="post-meta-divider">|</span>
            
              <span class="post-meta-item-icon">
                <i class="fa fa-folder-o"></i>
              </span>
              
                <span class="post-meta-item-text">分类于</span>
              
              
                <span itemprop="about" itemscope itemtype="http://schema.org/Thing">
                  <a href="/categories/数据库/" itemprop="url" rel="index">
                    <span itemprop="name">数据库</span>
                  </a>
                </span>

                
                
              
            </span>
          

          
            
          

          
          
             <span id="/2019/04/11/Service/MySql数据库/" class="leancloud_visitors" data-flag-title="MySql数据库">
               <span class="post-meta-divider">|</span>
               <span class="post-meta-item-icon">
                 <i class="fa fa-eye"></i>
               </span>
               
                 <span class="post-meta-item-text">阅读次数&#58;</span>
               
                 <span class="leancloud-visitors-count"></span>
             </span>
          

          

          
            <div class="post-wordcount">
              
                
                <span class="post-meta-item-icon">
                  <i class="fa fa-file-word-o"></i>
                </span>
                
                  <span class="post-meta-item-text">字数统计&#58;</span>
                
                <span title="字数统计">
                 1.7k 字
                </span>
              

              
                <span class="post-meta-divider">|</span>
              

              
                <span class="post-meta-item-icon">
                  <i class="fa fa-clock-o"></i>
                </span>
                
                  <span class="post-meta-item-text">阅读时长 &asymp;</span>
                
                <span title="阅读时长">
                   6 分钟
                </span>
              
            </div>
          

          
     
        </div>
      </header>
    

    
    
    
    <div class="post-body" itemprop="articleBody">

      
      

      
        <p>MySql数据库<br><a id="more"></a></p>
<h3 id="名称解释"><a href="#名称解释" class="headerlink" title="名称解释"></a>名称解释</h3><table>
<thead>
<tr>
<th>名称</th>
<th style="text-align:left">简述</th>
</tr>
</thead>
<tbody>
<tr>
<td>关系</td>
<td style="text-align:left">一个关系通常说的是一张表</td>
</tr>
<tr>
<td>元组</td>
<td style="text-align:left">表中的一行即为一个元组。</td>
</tr>
<tr>
<td>属性</td>
<td style="text-align:left">表中的一列即为一个属性；每个属性都有一个名称，称为属性名。</td>
</tr>
<tr>
<td>候选码</td>
<td style="text-align:left">表中的每个属性组，它可以唯一确定一个元组。</td>
</tr>
<tr>
<td>主码</td>
<td style="text-align:left">一个关系又多个候选码，选定其中一个为主码</td>
</tr>
<tr>
<td>域</td>
<td style="text-align:left">属性的取值范围</td>
</tr>
<tr>
<td>分量</td>
<td style="text-align:left">元组中的一个属性值</td>
</tr>
</tbody>
</table>
<h1 id="SQL语句"><a href="#SQL语句" class="headerlink" title="SQL语句"></a>SQL语句</h1><h3 id="基础语句："><a href="#基础语句：" class="headerlink" title="基础语句："></a>基础语句：</h3><ul>
<li>select - 从数据库中提取数据</li>
<li>update - 更新数据库中的数据</li>
<li>delete - 从数据库中删除数据</li>
<li>insert into - 向数据库中插入新数据</li>
<li>create table - 创建新表</li>
<li>alert table - 修改数据库表</li>
<li>drop table - 删除表</li>
<li>create index - 创建索引</li>
<li>drop index - 删除索引</li>
</ul>
<h3 id="常用语句："><a href="#常用语句：" class="headerlink" title="常用语句："></a>常用语句：</h3><p><code>show databases</code> 显示所有数据库 。<br><code>use database_name</code>  进入某个数据库 ， databases_name 为某个数据库名。<br><code>select * from table_name</code> 查询某个表的所有数据 ，table_name 为表名。<br><code>create database database_name</code> 创建数据库，其中database_name 为数据库名称<br><code>desc table_name</code> 查看一个表的结构<br><code>show create table table_name</code> 查看创建表的SQL语句<br><code>exit</code> 退出数据库 (仅仅断开了客户端和服务器的连接)</p>
<h3 id="查询语句"><a href="#查询语句" class="headerlink" title="查询语句"></a>查询语句</h3><h4 id="条件语句"><a href="#条件语句" class="headerlink" title="条件语句"></a>条件语句</h4><ul>
<li><code>OR</code>： 或者</li>
<li><code>AND</code>: 并且</li>
<li><code>NOT</code>：不符合该条件</li>
<li><code>=</code>：判断相等</li>
<li><code>&gt;</code>：判断大于</li>
<li><code>&gt;=</code>：判断大于或者等于</li>
<li><code>&lt;</code>：判断小于</li>
<li><code>&lt;=</code>：判断小于或者等于</li>
<li><code>&lt;&gt;</code>：判断不相等</li>
<li><code>LIKE</code>：判断相似</li>
</ul>
<p>练习：</p>
<ol>
<li>where 关键字后面的 score &gt;= 80 是条件。<br><code>select * from students where score &gt;= 80;</code></li>
<li>条件表达式用&lt;条件1&gt; AND &lt;条件2&gt;表达满足条件1并且满足条件2.符合条件“分数在80分或以上”，并且还符合条件“男生” , 就可以写：<br><code>select * from students where score &gt;= 80 AND gender = &#39;M&#39;;</code></li>
<li>条件表达式用&lt;条件1&gt; OR &lt;条件2&gt;表达满足条件1或者满足条件2。分数在80分或以上”或者“男生” , 可以写：<br><code>select * from students where score &gt;= 80 OR gender = &#39;M&#39;;</code></li>
<li>不是2班的学生<br><code>select * from students where NOT class_id = 2;</code><br>也可以写成：<br><code>select * from students where class_id &lt;&gt; 2;</code></li>
<li>查询分数在60分(含)~90分(含)之间的学生<br><code>select * from students where score &gt;= 60 AND score &lt;= 90;</code><br><code>select * from students where score between 60 and 90;</code></li>
</ol>
<h4 id="投影查询"><a href="#投影查询" class="headerlink" title="投影查询"></a>投影查询</h4><p>用<code>SELECT 列1, 列2, 列3 FROM ...</code>，让结果集仅包含指定列。这种操作称为投影查询。<br>还可以给每一个列名起别名，它的语法是：<code>SELECT 列1 别名1, 列2 别名2, 列3 别名3 FROM...</code><br>练习：</p>
<ol>
<li>从students表中返回id、score和name这三列<br><code>select id,score,name from students;</code></li>
<li>SELECT语句将列名score重命名为points，而id和name列名保持不变<br><code>select id,score points,name from students;</code></li>
</ol>
<h4 id="排序"><a href="#排序" class="headerlink" title="排序"></a>排序</h4><p>关键字：ORDER BY<br>默认是正序：ASC<br>如果有WHERE子句，那么ORDER BY子句要放到WHERE子句后面。<br>练习：</p>
<ol>
<li>按照成绩从低到高进行排序。正序 ASC<br><code>select id,score,name from students order by score;</code></li>
<li>按照成绩从高到低进行排序。倒序 DESC<br><code>select id,score,name from students order by score desc;</code></li>
<li>先按score列倒序，如果有相同分数的，再按gender列排序<br><code>select id ,score ,name,gender from students order by score desc , gender;</code></li>
<li>查询一班的学生成绩，并按照倒序排序<br><code>select * from students where class_id = 1 order by score desc;</code></li>
</ol>
<h4 id="聚合查询"><a href="#聚合查询" class="headerlink" title="聚合查询"></a>聚合查询</h4><table>
<thead>
<tr>
<th>函数</th>
<th>说明</th>
</tr>
</thead>
<tbody>
<tr>
<td>COUNT</td>
<td>统计数量</td>
</tr>
<tr>
<td>SUM</td>
<td>计算某一列的合计值，该列必须为数值类型</td>
</tr>
<tr>
<td>AVG</td>
<td>计算某一列的平均值，该列必须为数值类型</td>
</tr>
<tr>
<td>MAX</td>
<td>计算某一列的最大值</td>
</tr>
<tr>
<td>MIN</td>
<td>计算某一列的最小值</td>
</tr>
</tbody>
</table>
<p>注意：如果聚合查询的where条件没有匹配到任何行，COUNT()会返回0，<br>而SUM()、AVG()、MAX()、MIN()会返回NULL;</p>
<p>练习：</p>
<ol>
<li>查询students表中的一共有多少记录<br><code>select COUNT(*) from students;</code><br>可以给列名起个别名<br><code>select COUNT(*) num from students;</code></li>
<li>统计有多少男生<br><code>select COUNT(*) boys from students where gender = &#39;M&#39;;</code></li>
<li>统计男生的平均成绩<br><code>select AVG(score)  from students where gender = &#39;M&#39;;</code></li>
</ol>
<p>分组聚合<br>练习：</p>
<ol>
<li>统计各班级人数<br><code>select class_id,COUNT(*) num from students group by class_id;</code></li>
<li>统计各班的男生和女生人数<br><code>select class_id,gender,COUNT(*) num from students group by class_id,gender;</code></li>
<li>用一条SELECT查询查出每个班级的平均分<br><code>select class_id,AVG(score) from students group by class_id;</code></li>
<li>用一条SELECT查询查出每个班级的平均分 保留两位小数<br><code>select class_id,round(AVG(score),2) from students group by class_id;</code></li>
<li>查出每个班级男生和女生的平均分<br><code>select class_id,gender,round(avg(score),2) from students group by class_id,gender;</code></li>
</ol>
<h4 id="连接查询"><a href="#连接查询" class="headerlink" title="连接查询"></a>连接查询</h4><p>内连接：</p>
<ol>
<li>先确定主表，仍然使用<code>from &lt;表1&gt;</code>的语法;</li>
<li>再确定需要连接的表，使用<code>inner join &lt;表2&gt;</code>的语法；</li>
<li>然后确定连接条件，使用<code>ON &lt;条件...&gt;</code>，这里的条件是<code>students.class_id = classes.id</code>，表示students表的class_id列与classes表的id列相同的行需要连接；</li>
<li>可选：加上where子句，order by 等子句。</li>
</ol>
<p><img src="/images/数据库连接查询相关图.jpg" alt></p>
<p>练习：</p>
<ol>
<li>把每位学生对应的班级名称列出来.<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line">select s.id,s.name,s.class_id,c.name class_name,s.gender,s.score </span><br><span class="line">from students s </span><br><span class="line">inner join classes c </span><br><span class="line">ON s.class_id = c.id;</span><br></pre></td></tr></table></figure>
</li>
</ol>
<hr>
<h3 id="插入语句"><a href="#插入语句" class="headerlink" title="插入语句"></a>插入语句</h3><p>语法: <code>INSERT INTO &lt;表名&gt; (字段1, 字段2, ...) VALUES (值1, 值2, ...);</code><br>也可以一次性添加多条记录，只需在<code>VALUES</code>子句中指定多个记录值，每个记录用括号</p>
<p>例如：<br><figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line">INSERT INTO students (class_id, name, gender, score) VALUES</span><br><span class="line">  (1, &apos;大宝&apos;, &apos;M&apos;, 87),</span><br><span class="line">  (2, &apos;二宝&apos;, &apos;M&apos;, 81);</span><br></pre></td></tr></table></figure></p>
<p>练习：</p>
<ol>
<li>向students表插入一条新记录<br><code>INSERT INTO test_database.students (id, class_id, name, gender, score) VALUES (11, 3, &#39;小丽2&#39;, &#39;M&#39;, 85);</code></li>
</ol>
<h3 id="更新语句"><a href="#更新语句" class="headerlink" title="更新语句"></a>更新语句</h3><p>语法:<br><code>UPDATE &lt;表名&gt; SET 字段1=值1, 字段2=值2, ... WHERE ...;</code></p>
<p>练习：</p>
<ol>
<li>更新id为1的学生的姓名和分数两个字段<br><code>update students set name =&#39;大牛&#39;,score=66 where id = 1;</code></li>
<li>更新id = 5,6,7的记录<br><code>update students set name =&#39;大牛&#39;,score=66 where id &gt;=5 AND id &lt;=7;</code></li>
<li>把所有80分以下的同学的成绩加10分<br><code>update students set score = score + 10 where score &lt; 80;</code><br>注意:执行这句遇到了 1175 问题，执行 <code>SET SQL_SAFE_UPDATES = 0</code>解决;</li>
</ol>
<p>注意：UPDATE语句可以没有WHERE条件,假设执行<code>update students SET score=60;</code>,会使整个表所有的记录都被更新。最好先用select语句来测试where条件是否筛选出了期望的记录，然后再用update更新。</p>
<h3 id="删除语句"><a href="#删除语句" class="headerlink" title="删除语句"></a>删除语句</h3><p>语法：<br><code>DELETE FROM &lt;表名&gt; WHERE ...;</code></p>
<p>练习：</p>
<ol>
<li>删除id=1的记录<br><code>delete from students where id=1;</code></li>
</ol>
<p>注意：delete和update类似，不带where条件也可以执行。如果执行<code>delete from students</code>会删除整个表的数据</p>
<hr>
<p>笔记参考</p>
<blockquote>
<p><a href="http://www.runoob.com/sql/sql-syntax.html" target="_blank" rel="noopener">菜鸟教程</a><br><a href="https://www.liaoxuefeng.com/wiki/001508284671805d39d23243d884b8b99f440bfae87b0f4000/001509192416135a120ac09e03e4f94be1cf73a5da37e7d000" target="_blank" rel="noopener">雪峰老师</a></p>
</blockquote>

      
    </div>
    
    
    

    
        
       <div>
          <div>
    
        <div style="text-align:center;color: #ccc;font-size:14px;">-------------本文结束<i class="fa fa-paw"></i>感谢您的阅读-------------</div>
    
</div>
        </div>
      
    
 

    

    

    

    <footer class="post-footer">
      
        <div class="post-tags">
          
            <a href="/tags/Mysql/" rel="tag"># Mysql</a>
          
        </div>
      

      
      
      

      
        <div class="post-nav">
          <div class="post-nav-next post-nav-item">
            
              <a href="/2019/04/11/Service/服务器端相关的操作手册/" rel="next" title="服务器端相关的操作手册">
                <i class="fa fa-chevron-left"></i> 服务器端相关的操作手册
              </a>
            
          </div>

          <span class="post-nav-divider"></span>

          <div class="post-nav-prev post-nav-item">
            
              <a href="/2019/04/12/Service/NGINX相关笔记/" rel="prev" title="NGINX相关笔记">
                NGINX相关笔记 <i class="fa fa-chevron-right"></i>
              </a>
            
          </div>
        </div>
      

      
      
    </footer>
  </div>
  
  
  
  </article>



    <div class="post-spread">
      
    </div>
  </div>


          </div>
          


          

  



        </div>
        
          
  
  <div class="sidebar-toggle">
    <div class="sidebar-toggle-line-wrap">
      <span class="sidebar-toggle-line sidebar-toggle-line-first"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-middle"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-last"></span>
    </div>
  </div>

  <aside id="sidebar" class="sidebar">
    
    <div class="sidebar-inner">

      

      
        <ul class="sidebar-nav motion-element">
          <li class="sidebar-nav-toc sidebar-nav-active" data-target="post-toc-wrap">
            文章目录
          </li>
          <li class="sidebar-nav-overview" data-target="site-overview-wrap">
            站点概览
          </li>
        </ul>
      

      <section class="site-overview-wrap sidebar-panel">
        <div class="site-overview">
          <div class="site-author motion-element" itemprop="author" itemscope itemtype="http://schema.org/Person">
            
              <img class="site-author-image" itemprop="image" src="/uploads/avatar.jpg" alt="Dan">
            
              <p class="site-author-name" itemprop="name">Dan</p>
              <p class="site-description motion-element" itemprop="description">top top</p>
          </div>

          <nav class="site-state motion-element">

            
              <div class="site-state-item site-state-posts">
              
                <a href="/archives">
              
                  <span class="site-state-item-count">15</span>
                  <span class="site-state-item-name">日志</span>
                </a>
              </div>
            

            
              
              
              <div class="site-state-item site-state-categories">
                <a href="/categories/index.html">
                  <span class="site-state-item-count">7</span>
                  <span class="site-state-item-name">分类</span>
                </a>
              </div>
            

            
              
              
              <div class="site-state-item site-state-tags">
                <a href="/tags/index.html">
                  <span class="site-state-item-count">7</span>
                  <span class="site-state-item-name">标签</span>
                </a>
              </div>
            

          </nav>

          

          

          
          

          
          

          

        </div>
      </section>

      
      <!--noindex-->
        <section class="post-toc-wrap motion-element sidebar-panel sidebar-panel-active">
          <div class="post-toc">

            
              
            

            
              <div class="post-toc-content"><ol class="nav"><li class="nav-item nav-level-3"><a class="nav-link" href="#名称解释"><span class="nav-number">1.</span> <span class="nav-text">名称解释</span></a></li></ol><li class="nav-item nav-level-1"><a class="nav-link" href="#SQL语句"><span class="nav-number"></span> <span class="nav-text">SQL语句</span></a><ol class="nav-child"><li class="nav-item nav-level-3"><a class="nav-link" href="#基础语句："><span class="nav-number">1.</span> <span class="nav-text">基础语句：</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#常用语句："><span class="nav-number">2.</span> <span class="nav-text">常用语句：</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#查询语句"><span class="nav-number">3.</span> <span class="nav-text">查询语句</span></a><ol class="nav-child"><li class="nav-item nav-level-4"><a class="nav-link" href="#条件语句"><span class="nav-number">3.1.</span> <span class="nav-text">条件语句</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#投影查询"><span class="nav-number">3.2.</span> <span class="nav-text">投影查询</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#排序"><span class="nav-number">3.3.</span> <span class="nav-text">排序</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#聚合查询"><span class="nav-number">3.4.</span> <span class="nav-text">聚合查询</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#连接查询"><span class="nav-number">3.5.</span> <span class="nav-text">连接查询</span></a></li></ol></li><li class="nav-item nav-level-3"><a class="nav-link" href="#插入语句"><span class="nav-number">4.</span> <span class="nav-text">插入语句</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#更新语句"><span class="nav-number">5.</span> <span class="nav-text">更新语句</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#删除语句"><span class="nav-number">6.</span> <span class="nav-text">删除语句</span></a></li></ol></li></div>
            

          </div>
        </section>
      <!--/noindex-->
      

      

    </div>
  </aside>


        
      </div>
    </main>

    <footer id="footer" class="footer">
      <div class="footer-inner">
        

<div class="copyright">&copy; <span itemprop="copyrightYear">2020</span>
  <span class="with-love">
    <i class="fa fa-user"></i>
  </span>
  <span class="author" itemprop="copyrightHolder">Dan</span>

 

  
</div>













        







        
      </div>
    </footer>

    
      <div class="back-to-top">
        <i class="fa fa-arrow-up"></i>
        
      </div>
    

    

  </div>

  

<script type="text/javascript">
  if (Object.prototype.toString.call(window.Promise) !== '[object Function]') {
    window.Promise = null;
  }
</script>









  


  











  
  
    <script type="text/javascript" src="/lib/jquery/index.js?v=2.1.3"></script>
  

  
  
    <script type="text/javascript" src="/lib/fastclick/lib/fastclick.min.js?v=1.0.6"></script>
  

  
  
    <script type="text/javascript" src="/lib/jquery_lazyload/jquery.lazyload.js?v=1.9.7"></script>
  

  
  
    <script type="text/javascript" src="/lib/velocity/velocity.min.js?v=1.2.1"></script>
  

  
  
    <script type="text/javascript" src="/lib/velocity/velocity.ui.min.js?v=1.2.1"></script>
  

  
  
    <script type="text/javascript" src="/lib/fancybox/source/jquery.fancybox.pack.js?v=2.1.5"></script>
  

  
  
    <script type="text/javascript" src="/lib/canvas-nest/canvas-nest.min.js"></script>
  


  


  <script type="text/javascript" src="/js/src/utils.js?v=5.1.4"></script>

  <script type="text/javascript" src="/js/src/motion.js?v=5.1.4"></script>



  
  


  <script type="text/javascript" src="/js/src/affix.js?v=5.1.4"></script>

  <script type="text/javascript" src="/js/src/schemes/pisces.js?v=5.1.4"></script>



  
  <script type="text/javascript" src="/js/src/scrollspy.js?v=5.1.4"></script>
<script type="text/javascript" src="/js/src/post-details.js?v=5.1.4"></script>



  


  <script type="text/javascript" src="/js/src/bootstrap.js?v=5.1.4"></script>



  


  




	





  





  












  

  <script type="text/javascript">
    // Popup Window;
    var isfetched = false;
    var isXml = true;
    // Search DB path;
    var search_path = "search.xml";
    if (search_path.length === 0) {
      search_path = "search.xml";
    } else if (/json$/i.test(search_path)) {
      isXml = false;
    }
    var path = "/" + search_path;
    // monitor main search box;

    var onPopupClose = function (e) {
      $('.popup').hide();
      $('#local-search-input').val('');
      $('.search-result-list').remove();
      $('#no-result').remove();
      $(".local-search-pop-overlay").remove();
      $('body').css('overflow', '');
    }

    function proceedsearch() {
      $("body")
        .append('<div class="search-popup-overlay local-search-pop-overlay"></div>')
        .css('overflow', 'hidden');
      $('.search-popup-overlay').click(onPopupClose);
      $('.popup').toggle();
      var $localSearchInput = $('#local-search-input');
      $localSearchInput.attr("autocapitalize", "none");
      $localSearchInput.attr("autocorrect", "off");
      $localSearchInput.focus();
    }

    // search function;
    var searchFunc = function(path, search_id, content_id) {
      'use strict';

      // start loading animation
      $("body")
        .append('<div class="search-popup-overlay local-search-pop-overlay">' +
          '<div id="search-loading-icon">' +
          '<i class="fa fa-spinner fa-pulse fa-5x fa-fw"></i>' +
          '</div>' +
          '</div>')
        .css('overflow', 'hidden');
      $("#search-loading-icon").css('margin', '20% auto 0 auto').css('text-align', 'center');

      $.ajax({
        url: path,
        dataType: isXml ? "xml" : "json",
        async: true,
        success: function(res) {
          // get the contents from search data
          isfetched = true;
          $('.popup').detach().appendTo('.header-inner');
          var datas = isXml ? $("entry", res).map(function() {
            return {
              title: $("title", this).text(),
              content: $("content",this).text(),
              url: $("url" , this).text()
            };
          }).get() : res;
          var input = document.getElementById(search_id);
          var resultContent = document.getElementById(content_id);
          var inputEventFunction = function() {
            var searchText = input.value.trim().toLowerCase();
            var keywords = searchText.split(/[\s\-]+/);
            if (keywords.length > 1) {
              keywords.push(searchText);
            }
            var resultItems = [];
            if (searchText.length > 0) {
              // perform local searching
              datas.forEach(function(data) {
                var isMatch = false;
                var hitCount = 0;
                var searchTextCount = 0;
                var title = data.title.trim();
                var titleInLowerCase = title.toLowerCase();
                var content = data.content.trim().replace(/<[^>]+>/g,"");
                var contentInLowerCase = content.toLowerCase();
                var articleUrl = decodeURIComponent(data.url);
                var indexOfTitle = [];
                var indexOfContent = [];
                // only match articles with not empty titles
                if(title != '') {
                  keywords.forEach(function(keyword) {
                    function getIndexByWord(word, text, caseSensitive) {
                      var wordLen = word.length;
                      if (wordLen === 0) {
                        return [];
                      }
                      var startPosition = 0, position = [], index = [];
                      if (!caseSensitive) {
                        text = text.toLowerCase();
                        word = word.toLowerCase();
                      }
                      while ((position = text.indexOf(word, startPosition)) > -1) {
                        index.push({position: position, word: word});
                        startPosition = position + wordLen;
                      }
                      return index;
                    }

                    indexOfTitle = indexOfTitle.concat(getIndexByWord(keyword, titleInLowerCase, false));
                    indexOfContent = indexOfContent.concat(getIndexByWord(keyword, contentInLowerCase, false));
                  });
                  if (indexOfTitle.length > 0 || indexOfContent.length > 0) {
                    isMatch = true;
                    hitCount = indexOfTitle.length + indexOfContent.length;
                  }
                }

                // show search results

                if (isMatch) {
                  // sort index by position of keyword

                  [indexOfTitle, indexOfContent].forEach(function (index) {
                    index.sort(function (itemLeft, itemRight) {
                      if (itemRight.position !== itemLeft.position) {
                        return itemRight.position - itemLeft.position;
                      } else {
                        return itemLeft.word.length - itemRight.word.length;
                      }
                    });
                  });

                  // merge hits into slices

                  function mergeIntoSlice(text, start, end, index) {
                    var item = index[index.length - 1];
                    var position = item.position;
                    var word = item.word;
                    var hits = [];
                    var searchTextCountInSlice = 0;
                    while (position + word.length <= end && index.length != 0) {
                      if (word === searchText) {
                        searchTextCountInSlice++;
                      }
                      hits.push({position: position, length: word.length});
                      var wordEnd = position + word.length;

                      // move to next position of hit

                      index.pop();
                      while (index.length != 0) {
                        item = index[index.length - 1];
                        position = item.position;
                        word = item.word;
                        if (wordEnd > position) {
                          index.pop();
                        } else {
                          break;
                        }
                      }
                    }
                    searchTextCount += searchTextCountInSlice;
                    return {
                      hits: hits,
                      start: start,
                      end: end,
                      searchTextCount: searchTextCountInSlice
                    };
                  }

                  var slicesOfTitle = [];
                  if (indexOfTitle.length != 0) {
                    slicesOfTitle.push(mergeIntoSlice(title, 0, title.length, indexOfTitle));
                  }

                  var slicesOfContent = [];
                  while (indexOfContent.length != 0) {
                    var item = indexOfContent[indexOfContent.length - 1];
                    var position = item.position;
                    var word = item.word;
                    // cut out 100 characters
                    var start = position - 20;
                    var end = position + 80;
                    if(start < 0){
                      start = 0;
                    }
                    if (end < position + word.length) {
                      end = position + word.length;
                    }
                    if(end > content.length){
                      end = content.length;
                    }
                    slicesOfContent.push(mergeIntoSlice(content, start, end, indexOfContent));
                  }

                  // sort slices in content by search text's count and hits' count

                  slicesOfContent.sort(function (sliceLeft, sliceRight) {
                    if (sliceLeft.searchTextCount !== sliceRight.searchTextCount) {
                      return sliceRight.searchTextCount - sliceLeft.searchTextCount;
                    } else if (sliceLeft.hits.length !== sliceRight.hits.length) {
                      return sliceRight.hits.length - sliceLeft.hits.length;
                    } else {
                      return sliceLeft.start - sliceRight.start;
                    }
                  });

                  // select top N slices in content

                  var upperBound = parseInt('1');
                  if (upperBound >= 0) {
                    slicesOfContent = slicesOfContent.slice(0, upperBound);
                  }

                  // highlight title and content

                  function highlightKeyword(text, slice) {
                    var result = '';
                    var prevEnd = slice.start;
                    slice.hits.forEach(function (hit) {
                      result += text.substring(prevEnd, hit.position);
                      var end = hit.position + hit.length;
                      result += '<b class="search-keyword">' + text.substring(hit.position, end) + '</b>';
                      prevEnd = end;
                    });
                    result += text.substring(prevEnd, slice.end);
                    return result;
                  }

                  var resultItem = '';

                  if (slicesOfTitle.length != 0) {
                    resultItem += "<li><a href='" + articleUrl + "' class='search-result-title'>" + highlightKeyword(title, slicesOfTitle[0]) + "</a>";
                  } else {
                    resultItem += "<li><a href='" + articleUrl + "' class='search-result-title'>" + title + "</a>";
                  }

                  slicesOfContent.forEach(function (slice) {
                    resultItem += "<a href='" + articleUrl + "'>" +
                      "<p class=\"search-result\">" + highlightKeyword(content, slice) +
                      "...</p>" + "</a>";
                  });

                  resultItem += "</li>";
                  resultItems.push({
                    item: resultItem,
                    searchTextCount: searchTextCount,
                    hitCount: hitCount,
                    id: resultItems.length
                  });
                }
              })
            };
            if (keywords.length === 1 && keywords[0] === "") {
              resultContent.innerHTML = '<div id="no-result"><i class="fa fa-search fa-5x" /></div>'
            } else if (resultItems.length === 0) {
              resultContent.innerHTML = '<div id="no-result"><i class="fa fa-frown-o fa-5x" /></div>'
            } else {
              resultItems.sort(function (resultLeft, resultRight) {
                if (resultLeft.searchTextCount !== resultRight.searchTextCount) {
                  return resultRight.searchTextCount - resultLeft.searchTextCount;
                } else if (resultLeft.hitCount !== resultRight.hitCount) {
                  return resultRight.hitCount - resultLeft.hitCount;
                } else {
                  return resultRight.id - resultLeft.id;
                }
              });
              var searchResultList = '<ul class=\"search-result-list\">';
              resultItems.forEach(function (result) {
                searchResultList += result.item;
              })
              searchResultList += "</ul>";
              resultContent.innerHTML = searchResultList;
            }
          }

          if ('auto' === 'auto') {
            input.addEventListener('input', inputEventFunction);
          } else {
            $('.search-icon').click(inputEventFunction);
            input.addEventListener('keypress', function (event) {
              if (event.keyCode === 13) {
                inputEventFunction();
              }
            });
          }

          // remove loading animation
          $(".local-search-pop-overlay").remove();
          $('body').css('overflow', '');

          proceedsearch();
        }
      });
    }

    // handle and trigger popup window;
    $('.popup-trigger').click(function(e) {
      e.stopPropagation();
      if (isfetched === false) {
        searchFunc(path, 'local-search-input', 'local-search-result');
      } else {
        proceedsearch();
      };
    });

    $('.popup-btn-close').click(onPopupClose);
    $('.popup').click(function(e){
      e.stopPropagation();
    });
    $(document).on('keyup', function (event) {
      var shouldDismissSearchPopup = event.which === 27 &&
        $('.search-popup').is(':visible');
      if (shouldDismissSearchPopup) {
        onPopupClose();
      }
    });
  </script>





  

  
  <script src="https://cdn1.lncld.net/static/js/av-core-mini-0.6.4.js"></script>
  <script>AV.initialize("8LFgNJ231AoMbjrkXX1uVTlS-gzGzoHsz", "anKTYG98m9aHJfl3gbvzdANh");</script>
  <script>
    function showTime(Counter) {
      var query = new AV.Query(Counter);
      var entries = [];
      var $visitors = $(".leancloud_visitors");

      $visitors.each(function () {
        entries.push( $(this).attr("id").trim() );
      });

      query.containedIn('url', entries);
      query.find()
        .done(function (results) {
          var COUNT_CONTAINER_REF = '.leancloud-visitors-count';

          if (results.length === 0) {
            $visitors.find(COUNT_CONTAINER_REF).text(0);
            return;
          }

          for (var i = 0; i < results.length; i++) {
            var item = results[i];
            var url = item.get('url');
            var time = item.get('time');
            var element = document.getElementById(url);

            $(element).find(COUNT_CONTAINER_REF).text(time);
          }
          for(var i = 0; i < entries.length; i++) {
            var url = entries[i];
            var element = document.getElementById(url);
            var countSpan = $(element).find(COUNT_CONTAINER_REF);
            if( countSpan.text() == '') {
              countSpan.text(0);
            }
          }
        })
        .fail(function (object, error) {
          console.log("Error: " + error.code + " " + error.message);
        });
    }

    function addCount(Counter) {
      var $visitors = $(".leancloud_visitors");
      var url = $visitors.attr('id').trim();
      var title = $visitors.attr('data-flag-title').trim();
      var query = new AV.Query(Counter);

      query.equalTo("url", url);
      query.find({
        success: function(results) {
          if (results.length > 0) {
            var counter = results[0];
            counter.fetchWhenSave(true);
            counter.increment("time");
            counter.save(null, {
              success: function(counter) {
                var $element = $(document.getElementById(url));
                $element.find('.leancloud-visitors-count').text(counter.get('time'));
              },
              error: function(counter, error) {
                console.log('Failed to save Visitor num, with error message: ' + error.message);
              }
            });
          } else {
            var newcounter = new Counter();
            /* Set ACL */
            var acl = new AV.ACL();
            acl.setPublicReadAccess(true);
            acl.setPublicWriteAccess(true);
            newcounter.setACL(acl);
            /* End Set ACL */
            newcounter.set("title", title);
            newcounter.set("url", url);
            newcounter.set("time", 1);
            newcounter.save(null, {
              success: function(newcounter) {
                var $element = $(document.getElementById(url));
                $element.find('.leancloud-visitors-count').text(newcounter.get('time'));
              },
              error: function(newcounter, error) {
                console.log('Failed to create');
              }
            });
          }
        },
        error: function(error) {
          console.log('Error:' + error.code + " " + error.message);
        }
      });
    }

    $(function() {
      var Counter = AV.Object.extend("Counter");
      if ($('.leancloud_visitors').length == 1) {
        addCount(Counter);
      } else if ($('.post-title-link').length > 1) {
        showTime(Counter);
      }
    });
  </script>



  

  

  
  

  

  

  

</body>
</html>
